import classNames from "classnames";
import "./index.scss";
import { useDispatch, useSelector } from "react-redux";
import { fetchFoodsList, setActiveIndex } from "../../store/modules/takeaway";
import { useEffect } from "react";

const Menu = () => {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchFoodsList());
  }, [dispatch]);

  const { foodsList, activeIndex } = useSelector((state) => state.foods);
  const menus = foodsList.map((item) => ({ tag: item.tag, name: item.name })); // 将一组原始数据转换为另一种格式
  const handleToggle = (index) => {
    dispatch(setActiveIndex(index));
  };

  return (
    <nav className="list-menu">
      {/* 添加active类名会变成激活状态 */}
      {menus.map((item, index) => {
        return (
          <div
            onClick={() => handleToggle(index)}
            key={item.tag}
            className={classNames("list-menu-item", {
              active: activeIndex === index,
            })}
          >
            {item.name}
          </div>
        );
      })}
    </nav>
  );
};

export default Menu;
